"use client";
import React, {useState} from "react";
import {Core} from "cytoscape";
import {
  Tooltip,
  ActionIcon,
  Button,
  ColorInput,
  Group,
  Modal,
  NumberInput,
  Radio,
  Stack,
  Switch,
  RadioGroup,
} from "@mantine/core";
import {IconDownload} from "@tabler/icons-react";

export const IpdGraphDownload = ({cy}: {cy: Core}) => {
  const [opened, setOpened] = useState(false);
  const [withBg, setWithBg] = useState(true);
  const [scale, setScale] = useState(1);
  const [bgColor, setBgColor] = useState("#ffffff");
  const [format, setFormat] = useState<"png" | "jpg">("png");
  const [errors, setErrors] = useState({
    scale: "",
    bgColor: "",
  });

  // 数据验证函数
  const validate = () => {
    const newErrors: any = {scale: "", bgColor: ""};

    // 验证缩放比例
    if (scale < 1 || scale > 5) {
      newErrors.scale = "缩放比例必须在1到5之间";
    } else if (scale === null || scale === undefined) {
      newErrors.scale = "缩放比例不能为空";
    }

    // 如果选择了 JPG 并且启用了背景，背景色不能为空
    if (format === "jpg" && withBg && !bgColor) {
      newErrors.bgColor = "背景色不能为空";
    }

    setErrors(newErrors);
    return !Object.values(newErrors).some((error) => error);
  };

  const handleDownload = () => {
    if (!validate()) return;

    const options = {
      full: true,
      scale,
      ...(format === "jpg" && withBg ? {bg: bgColor} : {}),
    };

    const dataUrl = format === "png" ? cy.png(options) : cy.jpg(options);

    if (dataUrl) {
      const link = document.createElement("a");
      link.href = dataUrl;
      link.download = `graph.${format}`;
      link.click();
    }
    setOpened(false);
  };

  return (
    <>
      <Tooltip
        label="下载图片"
        withArrow
        position="bottom"
        transitionProps={{transition: "fade", duration: 300}}
      >
        <ActionIcon variant="default" onClick={() => setOpened(true)}>
          <IconDownload size={16} stroke={1.5} />
        </ActionIcon>
      </Tooltip>
      <Modal opened={opened} onClose={() => setOpened(false)} title="下载图片">
        <Stack gap="sm">
          <RadioGroup
            label="选择图片格式"
            value={format}
            onChange={(val) => setFormat(val as "png" | "jpg")}
          >
            <Group mt="xs">
              <Radio value="png" label="PNG（透明背景）" />
              <Radio value="jpg" label="JPG（可设置背景）" />
            </Group>
          </RadioGroup>

          <NumberInput
            label="缩放比例"
            value={scale}
            min={1}
            max={5}
            step={0.5}
            onChange={(val) => setScale(typeof val === "number" ? val : 1)}
            error={errors.scale}
          />

          {format === "jpg" && withBg && (
            <ColorInput
              label="背景色"
              value={bgColor}
              onChange={setBgColor}
              format="hex"
              swatches={["#ffffff", "#f0f0f0", "#000000", "#fffae6"]}
              error={errors.bgColor}
            />
          )}

          <Group justify="flex-end" mt="md">
            <Button variant="default" onClick={() => setOpened(false)}>
              取消
            </Button>
            <Button onClick={handleDownload}>下载</Button>
          </Group>
        </Stack>
      </Modal>
    </>
  );
};
